class Customer {
    /**
     * 获取用户信息
     * @api {GET}         /                            获取用户信息
     * @apiName           /customer
     * @apiGroup          Customer
     * @apiVersion 0.1.0
     * @apiParam          {Int}            page        页数
     * @apiParam          {Int}            limit       条数
     * @apiParam          {String}         keywords    关键字
     * @apiSuccessExample Success-Response:
     * {
        "code": 0,
        "msg": "success",
        "data": {
        "count": 1,
        "rows": [
            {
                "id": 7,
                "username": "editor",
                "avatar": "http://47.92.129.24/static/upload/20190604/90a4cead0df99.jpeg",
                "role_id": 2,
                "contract": 0.5,
                "status": true,
                "phone": 15632325645
            }
         ]
        }
      }
     */
    async index(ctx) {
        const {
            db,
            Op,
            request: {
                query: { page = 1, limit = 10, keywords = '' }
            }
        } = ctx;

        let condition = {
            limit: parseInt(limit),
            offset: (parseInt(page) - 1) * 10,
            include: {
                as: 'membersInfo',
                required: true,
                model: db.Members
            }
        };

        //如果关键字不为空
        if (keywords.trim()) {
            condition.where = {
                [Op.or]: [
                    { nickName: { [Op.like]: '%' + keywords.trim() + '%' } },
                    { phone: { [Op.like]: '%' + keywords.trim() + '%' } }
                ]
            };
        }

        // 判断权限
        let data = await db.User.findAndCountAll(condition);
        ctx.success(data);
    }
    /**
     * 禁用用户
     * @api {PUT}         /:id                            禁用用户
     * @apiName           /customer
     * @apiGroup          Customer
     * @apiVersion 0.1.0
     * @apiSuccessExample Success-Response:
     * {
        "code": 0,
        "msg": "success",
        "data": []
      }
     */
    async edit(ctx) {
        const {
            db,
            params: { id }
        } = ctx;

        let data = await db.User.findOne({ where: { id: id } });
        if (data.status) {
            data.status = 0;
        } else {
            data.status = 1;
        }
        data.save();
        ctx.success();
    }
    /**
     * 删除
     * @api {PUT}         /:id                            删除
     * @apiName           /customer
     * @apiGroup          Customer
     * @apiVersion 0.1.0
     * @apiSuccessExample Success-Response:
     * {
        "code": 0,
        "msg": "success",
        "data": []
      }
     */
    async deletes(ctx) {
        const {
            db,
            params: { id }
        } = ctx;
        db.User.destroy({ where: { id: id } });
        ctx.success();
    }
    /**
     * 获取用户消费明细
     * @api {GET}         /detail                    获取用户消费明细
     * @apiName           /customer/detail
     * @apiGroup          Customer
     * @apiVersion 0.1.0
     * @apiParam          {Int}            id         ID
     * @apiParam          {Int}            page       页数
     * @apiParam          {Int}            limit      条数
     * @apiSuccessExample Success-Response:
     * {
        "code": 0,
        "msg": "success",
        "data": {
            {
                "id": 2,
                "userId": 3,
                "merchantId": 7,
                "deviceId": 1,
                "address": "四川省成都市双流区麓山大道一段8号",
                "amount": "30.00",
                "payment": "会员抵扣",
                "status": true,
                "createdAt": "2019-06-04T07:48:38.000Z",
                "updatedAt": "2019-06-04T07:48:41.000Z"
            }
        }
      }
     */
    async detail(ctx) {
        const {
            db,
            request: {
                query: { id, limit = 10, page = 1 }
            }
        } = ctx;

        let condition = {
            limit: parseInt(limit),
            offset: (parseInt(page) - 1) * 10,
            where: {
                userId: id
            }
        };

        let data = await db.Use.findAndCountAll(condition);
        ctx.success(data);
    }
    /**
     * 改变会员
     * @api {PUT}         /change                     改变会员
     * @apiName           /change
     * @apiGroup          Customer
     * @apiVersion 0.1.0
     * @apiParam          {Int}            userId      用户ID
     * @apiParam          {Int}            memberId    会员卡ID
     * @apiParam          {Int}            group       组
     * @apiSuccessExample Success-Response:
     * {
        "code": 0,
        "msg": "success",
        "data": {}
      }
     */
    async change(ctx) {
        const {
            db,
            model,
            request: {
                body: { userId, memberId, group }
            }
        } = ctx;

        if (ctx.user.User.role.role !== 'admin') {
            ctx.errors('暂无权限');
            return;
        }

        if (!userId) {
            ctx.errors('参数错误');
            return;
        }

        if (!memberId) {
            ctx.errors('参数错误');
            return;
        }

        if (!group) {
            ctx.errors('请选择类型');
            return;
        }

        const member = await db.Members.findOne({ where: { id: memberId } });

        const user = await db.User.findOne({ where: { id: userId } });

        let transaction;
        try {
            transaction = await model.transaction();
            // 更新用户
            let par = {
                memberId: member.id,
                leftDay: user.leftDay + member.day * 86400, //续命
                member: member.actualPrice
            };
            // 判断
            if (!user.buyMemberTime) {
                par.buyMemberTime = Math.round(new Date() / 1000);
            }

            if (!user.endMemberTime) {
                par.endMemberTime =
                    Math.round(new Date() / 1000) + member.day * 86400;
            } else {
                par.endMemberTime = user.endMemberTime + member.day * 86400;
            }

            await db.User.update(par, {
                where: {
                    id: userId
                }
            });
            // 自动添加购买记录
            let res = {
                userId: userId,
                price: member.actualPrice,
                type: member.desc,
                status: 1
            };

            if (parseInt(group) !== 1) {
                res.type = '(赠送)' + member.desc;
            }

            await db.Buy.upsert(res);
            // 提交事务
            await transaction.commit();
            ctx.success(null, '购买成功');
        } catch (e) {
            console.log(e);
            // 回滚
            await transaction.rollback();
            ctx.body = 'FAIL';
            return;
        }
    }
}
module.exports = new Customer();
